/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package tallerfinal.view;

import java.awt.Component;
import java.awt.event.ItemEvent;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.text.NumberFormat;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JFormattedTextField;
import javax.swing.JOptionPane;
import javax.swing.text.DefaultFormatterFactory;
import javax.swing.text.NumberFormatter;
import tallerfinal.controller.OptimizationController;
import tallerfinal.util.distributions.Generator;
import tallerfinal.util.distributions.factory.GeneratorsFactory;
import tallerfinal.util.enums.DistributionsName;
import tallerfinal.view.distributions.GeneratorView;
import tallerfinal.view.distributions.factory.GeneratorViewFactory;

/**
 *
 * @author ricardo
 */
public class DataForm extends javax.swing.JPanel {

    private final static String newline = "\n";
    private OptimizationController controller;
    private int c;
    private boolean revisionEn = false;
    private Generator<?> distDemanda;
    private Generator<?> distTiempoEntrega;
    private Generator<?> distTiempoDemanda;
    private double reviewCost;
    private int n;
    private double unitaryCost;
    private double orderCost;
    private double holdCost;
    private double shortageCost;
    private int inventarioInicial;
    private int A;
    private int B;
    private String nameF;
    FileWriter fichero = null;
    PrintWriter pw = null;
    private String distT;
    private String distPD;
    private String distTde;

    /**
     * Creates new form DataForm
     */
    public DataForm() {
        initComponents();
        revisionCostLabel.setVisible(false);
        revisionCostField.setVisible(false);
        jPanel2.setVisible(false);

    }

    public JFormattedTextField getParamField() {
        return paramAField;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel3 = new javax.swing.JPanel();
        paramA = new javax.swing.JLabel();
        paramAField = new javax.swing.JFormattedTextField();
        paramB = new javax.swing.JLabel();
        paramBField = new javax.swing.JFormattedTextField();
        jLabel2 = new javax.swing.JLabel();
        invInicialF = new javax.swing.JFormattedTextField();
        jLabel6 = new javax.swing.JLabel();
        unitaryCostF = new javax.swing.JFormattedTextField(new DefaultFormatterFactory(new NumberFormatter(NumberFormat.getCurrencyInstance()),new NumberFormatter(NumberFormat.getCurrencyInstance()),new NumberFormatter(NumberFormat.getNumberInstance())));
        jLabel7 = new javax.swing.JLabel();
        ordenCostF = new javax.swing.JFormattedTextField(new DefaultFormatterFactory(new NumberFormatter(NumberFormat.getCurrencyInstance()),new NumberFormatter(NumberFormat.getCurrencyInstance()),new NumberFormatter(NumberFormat.getNumberInstance())));
        jLabel8 = new javax.swing.JLabel();
        holdCostF = new javax.swing.JFormattedTextField(new DefaultFormatterFactory(new NumberFormatter(NumberFormat.getCurrencyInstance()),new NumberFormatter(NumberFormat.getCurrencyInstance()),new NumberFormatter(NumberFormat.getNumberInstance())));
        jLabel9 = new javax.swing.JLabel();
        missingCostF = new javax.swing.JFormattedTextField(new DefaultFormatterFactory(new NumberFormatter(NumberFormat.getCurrencyInstance()),new NumberFormatter(NumberFormat.getCurrencyInstance()),new NumberFormatter(NumberFormat.getNumberInstance())));
        revisionCostLabel = new javax.swing.JLabel();
        revisionCostField = new javax.swing.JFormattedTextField(new DefaultFormatterFactory(new NumberFormatter(NumberFormat.getCurrencyInstance()),new NumberFormatter(NumberFormat.getCurrencyInstance()),new NumberFormatter(NumberFormat.getNumberInstance())));
        jLabel3 = new javax.swing.JLabel();
        distProbDem = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        distTiempoEn = new javax.swing.JComboBox();
        jLabel10 = new javax.swing.JLabel();
        distTimeDemandas = new javax.swing.JComboBox();
        jLabel11 = new javax.swing.JLabel();
        yearF = new javax.swing.JFormattedTextField();
        jLabel12 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        resultadosArea = new javax.swing.JTextArea();

        setBackground(new java.awt.Color(255, 255, 255));
        setLayout(new java.awt.BorderLayout());

        jPanel3.setBackground(new java.awt.Color(255, 255, 255));
        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true), "Introducion de Datos"));
        jPanel3.setPreferredSize(new java.awt.Dimension(350, 300));
        jPanel3.setLayout(new java.awt.GridLayout(13, 2));
        jPanel3.add(paramA);

        paramAField.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(java.text.NumberFormat.getIntegerInstance())));
        jPanel3.add(paramAField);
        jPanel3.add(paramB);

        paramBField.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(java.text.NumberFormat.getIntegerInstance())));
        jPanel3.add(paramBField);

        jLabel2.setText("Inventario Inicial");
        jPanel3.add(jLabel2);

        invInicialF.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(java.text.NumberFormat.getIntegerInstance())));
        jPanel3.add(invInicialF);

        jLabel6.setText("Costo unitario ($/unidad):");
        jPanel3.add(jLabel6);

        jPanel3.add(unitaryCostF);

        jLabel7.setText("Costo de orden ($/lote):");
        jPanel3.add(jLabel7);

        jPanel3.add(ordenCostF);

        jLabel8.setText("Costo de mantenimiento ($/unidad):");
        jPanel3.add(jLabel8);

        jPanel3.add(holdCostF);

        jLabel9.setText("Costo de Escasez ($/unidad):");
        jPanel3.add(jLabel9);

        jPanel3.add(missingCostF);

        revisionCostLabel.setText("Costo de Revision ($/revision):");
        jPanel3.add(revisionCostLabel);

        jPanel3.add(revisionCostField);

        jLabel3.setText("Distribucion de Prob. de la demanda:");
        jPanel3.add(jLabel3);

        distProbDem.setModel(new DefaultComboBoxModel(DistributionsName.values()));
        distProbDem.setRenderer(new PromptComboBoxRenderer("Select Distribution"));
        distProbDem.setSelectedIndex(-1);
        distProbDem.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                distProbDemItemStateChanged(evt);
            }
        });
        jPanel3.add(distProbDem);

        jLabel1.setText("Distribucion de Prob. del tiempo de entrega: ");
        jPanel3.add(jLabel1);

        distTiempoEn.setModel(new DefaultComboBoxModel(DistributionsName.values()));
        distTiempoEn.setRenderer(new PromptComboBoxRenderer("Select Distribution"));
        distTiempoEn.setSelectedIndex(-1);
        distTiempoEn.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                distTiempoEnItemStateChanged(evt);
            }
        });
        jPanel3.add(distTiempoEn);

        jLabel10.setText("Distribucion de Prob. tiempo entre demanda: ");
        jPanel3.add(jLabel10);

        distTimeDemandas.setModel(new DefaultComboBoxModel(DistributionsName.values()));
        distTimeDemandas.setRenderer(new PromptComboBoxRenderer("Select Distribution"));
        distTimeDemandas.setSelectedIndex(-1);
        distTimeDemandas.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                distTimeDemandasItemStateChanged(evt);
            }
        });
        jPanel3.add(distTimeDemandas);

        jLabel11.setText("Duracion del año: ");
        jPanel3.add(jLabel11);

        yearF.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#0"))));
        jPanel3.add(yearF);
        jPanel3.add(jLabel12);

        jButton1.setText("Optimizar");
        jButton1.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/tallerfinal/resources/optimizacion.png"))); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        jPanel3.add(jButton1);

        add(jPanel3, java.awt.BorderLayout.CENTER);

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));
        jPanel1.setLayout(new java.awt.BorderLayout());

        jTextArea1.setEditable(false);
        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);

        jPanel1.add(jScrollPane1, java.awt.BorderLayout.CENTER);

        add(jPanel1, java.awt.BorderLayout.SOUTH);

        jPanel2.setBackground(new java.awt.Color(255, 255, 255));
        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true), "Resultados"));
        jPanel2.setPreferredSize(new java.awt.Dimension(500, 300));
        jPanel2.setLayout(new java.awt.BorderLayout());

        resultadosArea.setColumns(20);
        resultadosArea.setRows(5);
        jScrollPane2.setViewportView(resultadosArea);

        jPanel2.add(jScrollPane2, java.awt.BorderLayout.CENTER);

        add(jPanel2, java.awt.BorderLayout.EAST);
    }// </editor-fold>//GEN-END:initComponents

    private void distProbDemItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_distProbDemItemStateChanged
        // TODO add your handling code here:
        if (evt.getStateChange() == ItemEvent.SELECTED) {
            if (evt.getItem() instanceof DistributionsName) {
                DistributionsName item = (DistributionsName) evt.getItem();
                try {
                    GeneratorView panel = GeneratorViewFactory.getInstance().createGenerator(item);
                    int o = JOptionPane.showConfirmDialog(null, panel, "Digite los valores de la distribucion", JOptionPane.OK_CANCEL_OPTION);
                    if (o == JOptionPane.OK_OPTION) {
                        try {
                            distDemanda = GeneratorsFactory.getInstance().createGenerator(item, panel.getData());
                            distPD = panel.tosString();
                            jTextArea1.append(distPD + newline);
                        } catch (NoSuchMethodException | InstantiationException | InvocationTargetException | IllegalAccessException ex) {
                            Logger.getLogger(DataForm.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                } catch (NoSuchMethodException | InstantiationException | InvocationTargetException | IllegalAccessException ex) {
                    Logger.getLogger(DataForm.class.getName()).log(Level.SEVERE, null, ex);
                }

            }
        }
    }//GEN-LAST:event_distProbDemItemStateChanged

    private void distTiempoEnItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_distTiempoEnItemStateChanged
        if (evt.getStateChange() == ItemEvent.SELECTED) {
            if (evt.getItem() instanceof DistributionsName) {
                DistributionsName item = (DistributionsName) evt.getItem();
                try {
                    GeneratorView panel = GeneratorViewFactory.getInstance().createGenerator(item);
                    int o = JOptionPane.showConfirmDialog(null, panel, "Digite los valores de la distribucion", JOptionPane.OK_CANCEL_OPTION);
                    if (o == JOptionPane.OK_OPTION) {
                        try {
                            distTiempoEntrega = GeneratorsFactory.getInstance().createGenerator(item, panel.getData());
                            distT = panel.tosString();
                            jTextArea1.append(distT + newline);

                        } catch (NoSuchMethodException | InstantiationException | InvocationTargetException | IllegalAccessException ex) {
                            Logger.getLogger(DataForm.class.getName()).log(Level.SEVERE, null, ex);
                            System.out.println("fallo");
                        }
                    }
                } catch (NoSuchMethodException | InstantiationException | InvocationTargetException | IllegalAccessException ex) {
                    Logger.getLogger(DataForm.class.getName()).log(Level.SEVERE, null, ex);
                }

            }
        }
    }//GEN-LAST:event_distTiempoEnItemStateChanged

    private void distTimeDemandasItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_distTimeDemandasItemStateChanged
        if (evt.getStateChange() == ItemEvent.SELECTED) {
            if (evt.getItem() instanceof DistributionsName) {
                DistributionsName item = (DistributionsName) evt.getItem();
                try {
                    GeneratorView panel = GeneratorViewFactory.getInstance().createGenerator(item);
                    int o = JOptionPane.showConfirmDialog(null, panel, "Digite los valores de la distribucion", JOptionPane.OK_CANCEL_OPTION);
                    if (o == JOptionPane.OK_OPTION) {
                        try {
                            distTiempoDemanda = GeneratorsFactory.getInstance().createGenerator(item, panel.getData());
                            distTde = panel.tosString();
                            jTextArea1.append(distTde + newline);

                        } catch (NoSuchMethodException | InstantiationException | InvocationTargetException | IllegalAccessException ex) {
                            Logger.getLogger(DataForm.class.getName()).log(Level.SEVERE, null, ex);
                            System.out.println("fallo");
                        }
                    }
                } catch (NoSuchMethodException | InstantiationException | InvocationTargetException | IllegalAccessException ex) {
                    Logger.getLogger(DataForm.class.getName()).log(Level.SEVERE, null, ex);
                }

            }
        }
    }//GEN-LAST:event_distTimeDemandasItemStateChanged

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        A = ((Number) paramAField.getValue()).intValue();
        B = ((Number) paramBField.getValue()).intValue();
        n = ((Number) yearF.getValue()).intValue();
        unitaryCost = ((Number) unitaryCostF.getValue()).doubleValue();
        orderCost = ((Number) ordenCostF.getValue()).doubleValue();
        holdCost = ((Number) holdCostF.getValue()).doubleValue();
        shortageCost = ((Number) missingCostF.getValue()).doubleValue();
        inventarioInicial = ((Number) invInicialF.getValue()).intValue();

        if (revisionEn) {
            reviewCost = ((Number) revisionCostField.getValue()).doubleValue();

            controller = new OptimizationController(c, reviewCost, A, B, n, unitaryCost, orderCost, holdCost, shortageCost, distDemanda, distTiempoEntrega, distTiempoDemanda, inventarioInicial);
        } else {

            controller = new OptimizationController(c, A, B, n, unitaryCost, orderCost, holdCost, shortageCost, distDemanda, distTiempoEntrega, distTiempoDemanda, inventarioInicial);

        }
        if (controller != null) {
            disableAll();
            try {
                String r = controller.tabuSearch();
                NumberFormat f = NumberFormat.getCurrencyInstance();

                resultadosArea.append("Datos del Modelo: " + newline + newline);
                resultadosArea.append("Inventario inicial = " + inventarioInicial + " Unidades" + newline);
                resultadosArea.append("Años en dias = " + n + newline);
                resultadosArea.append("Costo unitario = " + f.format(unitaryCost) + newline);
                resultadosArea.append("Costos de Adquisicion = " + f.format(orderCost) + newline);
                resultadosArea.append("Costo de mantenimiento = " + f.format(holdCost) + newline);
                resultadosArea.append("Costo de perdidas = " + f.format(shortageCost) + newline);
                if (revisionEn) {
                    resultadosArea.append("Costo de revision = " + f.format(reviewCost) + newline);
                }
                resultadosArea.append("Distribucion Demanda = " + distPD + newline);
                resultadosArea.append("Distribucion Tiempo de entrega = " + distT + newline);
                resultadosArea.append("Distribucion Tiempo Demanda = " + distTde + newline);

                resultadosArea.append(newline + newline + "Datos Iniciales de la Busqueda Tabu:" + newline + newline);
                resultadosArea.append(paramA.getText() + " = " + A + newline);
                resultadosArea.append(paramB.getText() + " = " + B + newline);
                resultadosArea.append(newline + newline + "Resultados de la Busqueda Tabu:" + newline + newline);
                resultadosArea.append(r);

                jPanel2.setVisible(true);
                crearFuchero();
            } catch (Exception e) {
                JOptionPane.showMessageDialog(null, "Ha ocurrido un error", "Mensaje de Error", JOptionPane.ERROR_MESSAGE);
            }
        }
    }//GEN-LAST:event_jButton1ActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox distProbDem;
    private javax.swing.JComboBox distTiempoEn;
    private javax.swing.JComboBox distTimeDemandas;
    private javax.swing.JFormattedTextField holdCostF;
    private javax.swing.JFormattedTextField invInicialF;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JFormattedTextField missingCostF;
    private javax.swing.JFormattedTextField ordenCostF;
    private javax.swing.JLabel paramA;
    private javax.swing.JFormattedTextField paramAField;
    private javax.swing.JLabel paramB;
    private javax.swing.JFormattedTextField paramBField;
    private javax.swing.JTextArea resultadosArea;
    private javax.swing.JFormattedTextField revisionCostField;
    private javax.swing.JLabel revisionCostLabel;
    private javax.swing.JFormattedTextField unitaryCostF;
    private javax.swing.JFormattedTextField yearF;
    // End of variables declaration//GEN-END:variables

    void setOption(int c) {
        this.c = c;
        switch (c) {
            case 0:
                paramA.setText("Q (unidades a pedir)");
                paramB.setText("t (dias de revision)");
                revisionCostLabel.setVisible(true);
                revisionCostField.setVisible(true);
                revisionEn = true;
                break;
            case 1:
                paramA.setText("Q (unidades a pedir)");
                paramB.setText("r (nivel minimo de Inv.)");
                break;
            case 2:
                paramA.setText("R (nivel maximo de Inv.)");
                paramB.setText("t (dias de revision)");
                revisionCostLabel.setVisible(true);
                revisionCostField.setVisible(true);
                revisionEn = true;

                break;
            case 3:
                paramA.setText("R (Nivel maximo de Inv.)");
                paramB.setText("r (Punto de Pedido)");
                break;
        }
    }

    private void disableAll() {
        for (Component object : jPanel3.getComponents()) {
            object.setEnabled(false);
        }
    }

    public void setFileName(String nameF) {
        this.nameF = nameF;
    }

    private void crearFuchero() {
        boolean success = (new File("resultados")).mkdir();
        if (success) {
            System.out.println("Directory: "
                    + "resultados" + " created");
        }
        try {
            fichero = new FileWriter("resultados/" + nameF + ".txt");
            pw = new PrintWriter(fichero);
            pw.println(resultadosArea.getText());
        } catch (IOException ex) {
            Logger.getLogger(DataForm.class.getName()).log(Level.SEVERE, null, ex);
        } finally {

            try {
                if (null != fichero) {
                    fichero.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
    }
}
